package com.mashibing.mq;

import javax.jms.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Serializable;

/**
 * MQ里放一些text文本 ，一些可序列化对象，
 * MQ里还可以放一些小文件，比如JSON XML等
 */
public class MyListener implements MessageListener {

    @Override
    public void onMessage(Message message) {

        if(message instanceof TextMessage){
            //这里就不用receive了，直接取message即可 、  receive是阻塞的，监听器是异步的
            TextMessage textMessage = (TextMessage)message;
            try {
                System.out.println(textMessage.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }else if (message instanceof ObjectMessage){
            ObjectMessage objectMessage = (ObjectMessage)message;
            try {
                Girl girl = (Girl) objectMessage.getObject();
                System.out.println(girl.getName() +"  "+ girl.getAge() +"  "+ girl.getPrice());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }else if(message instanceof BytesMessage){
            BytesMessage bytesMessage = (BytesMessage)message;
            try {
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream("c:/dev/aa.txt");
                } catch (FileNotFoundException e2) {
                    e2.printStackTrace();
                }
                byte[] by = new byte[1024];
                int len = 0 ;
                try {
                    while((len = bytesMessage.readBytes(by))!= -1){
                        out.write(by,0,len);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(message instanceof MapMessage) {
            MapMessage mapMessage = (MapMessage)message;
            System.out.println("mapMessage:" + mapMessage);
            try {
                System.out.println("mapMessage:" + mapMessage.getString("name"));
                System.out.println("mapMessage:" + mapMessage.getInt("age"));
                System.out.println("mapMessage:" + mapMessage.getDouble("price"));
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }








    }
}
